import React, {Component} from 'react';
import "../../styles/pages/map.scss"
import cityPoints from "../../assets/js/cityPosotion.js"

class Map extends Component {
    state = {
        center: cityPoints['桂林市'],
    }

    componentDidMount () {
        this.initMap();
        // this.drawLine()
        this.drawInnerLine()
    }

    changeData = () => {
        // let data = require('../../assets/JSON/map/country.json')
        // let arr = []
        // data.map(item => {
        //     let a = item.geometry.coordinates[0][0]
        //     arr.push(...a)
        // })
        // let boundary = JSON.stringify(arr)
        // let blob = new Blob([boundary], {type: "application/json;charset=utf-8"});
        // this.downloadFile(blob, '桂林市区县JSON')
    }
    initMap = () => {
        this.map = new window.BMapGL.Map("map");// 创建Map实例
        let {center} = this.state
        this.map.centerAndZoom(new window.BMapGL.Point(...center), 9);  // 初始化地图,设置中心点坐标和地图级别
        this.map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
        this.addControl()
        this.addCenterMarker()
        this.cityMark()
        let geocoder = new BMapGL.Geocoder()// 创建标注
        this.map.addEventListener('click', (params) => {
            //console.log('--->鼠标点击位置', params)
        })
    }
    // 添加比例尺控件和缩放控件
    addControl = () => {
        let scaleCtrl = new window.BMapGL.ScaleControl();  // 添加比例尺控件
        this.map.addControl(scaleCtrl);
        let zoomCtrl = new window.BMapGL.ZoomControl();  // 添加缩放控件
        this.map.addControl(zoomCtrl);
    }
    // 添加西安和桂林中心点
    addCenterMarker = () => {
        let {center} = this.state
        this.createPoint(center);
        this.createPoint(cityPoints['西安市'], '西安市')
        this.createPoint(cityPoints['桂林电网'], '桂林电网')
        this.createPoint(cityPoints['昆明机场'], '昆明机场')
    }
    createPoint = (center, str) => {
        let point = new BMapGL.Point(...center);
        let marker = new BMapGL.Marker(point);
        let strInfo = str ? str : ''
        marker.addEventListener('click', (params) => {
            let {latLng} = params
            let opts = {width: 250, height: 100, title: `Hello${strInfo}`}
            let str = `当前坐标点如下:<br/>${latLng.lat}<br/> ${latLng.lng}`
            let infoWindow = new BMapGL.InfoWindow(str, opts);  // 创建信息窗口对象
            this.map.openInfoWindow(infoWindow, point);
            this.map.centerAndZoom(point, 9);
        }, {passive: true})
        this.map.addOverlay(marker);
    }
    strToArray = (str) => {
        let res = []
        str.split(';').map(item => {
            if (item) {
                let itemArr = []
                item.split(',').map(val => {
                    itemArr.push(Number(val))
                })
                res.push(itemArr)
            }
        })
        return res
    }
    downloadFile = (blob, name) => {
        let link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.target = '_blank'
        link.download = decodeURI(name)  // 下载的文件名称
        document.body.appendChild(link)  // 添加创建的 a 标签 dom节点
        link.click()  // 下载
        document.body.removeChild(link)  // 移除节点
    }
    changeMap = (type) => {
        let o = {
            '1': BMAP_NORMAL_MAP,
            '2': BMAP_EARTH_MAP,
            '3': BMAP_SATELLITE_MAP
        }
        this.map.setMapType(o[type]);
        let bd = new BMapGL.Boundary();
        let arr_area = ['莲湖区', '碑林区', '未央区', '新城区', '灞桥区', '雁塔区', '长安区', '高陵区']
        let arr_color = ['#4e0101', '#4e1f01', '#4e2d01', '#4e4501', '#414e01', '#4e0101', '#4e0101', '#4e0101']
        bd.get('碑林区', (rs) => {
            let xiAnInner = rs['boundaries'][0]
            let hole = new BMapGL.Polygon([xiAnInner], {
                fillColor: 'blue',
                fillOpacity: 0.2
            });
            this.map.addOverlay(hole);
        });
    }
    downloadJSON = () => {
        let bd = new BMapGL.Boundary();
        bd.get('桂林市', (rs) => {
            let xiAnInner = rs['boundaries'][0]
            let boundary = JSON.stringify(this.strToArray(xiAnInner))
            let blob = new Blob([boundary], {type: "application/json;charset=utf-8"});
            this.downloadFile(blob, '桂林市JSON')
        });
    }
    dealLineData = () => {
        // let lineData = require("../../assets/JSON/map/gui-lin.json")
        let lineData = require("../../assets/JSON/map/file.json")
        return lineData.map(item => new BMapGL.Point(item[0], item[1]))
    }
    // 绘制桂林外部线
    drawLine = () => {
        let polyline = new BMapGL.Polyline(this.dealLineData(), {
            strokeColor: "#048df3",
            strokeWeight: 10,
            strokeOpacity: 1
        });
        this.map.addOverlay(polyline);
    }
    //绘制桂林内部部线
    drawInnerLine = () => {
        let lineData = require("../../assets/JSON/map/country.json")
        lineData.map(val => {
            let arr = val.map(item => new BMapGL.Point(item[0], item[1]))
            let polyline = new BMapGL.Polyline(arr, {
                strokeColor: "#048df3",
                strokeWeight: 2,
                strokeOpacity: 0.5
            });
            this.map.addOverlay(polyline);
        })

    }
    // 市外虚化
    cityMark = () => {
        //右上=>右下=>左下=>左上
        let outside = '136.0,59.0;136.0,3.0;70.0,3.0;70.0,59.0'
        let bd = new BMapGL.Boundary();
        bd.get('桂林市', (rs) => {
            let hole = new BMapGL.Polygon([outside, rs.boundaries[0]], {
                fillColor: '#767981',
                fillOpacity: 0.2,
                strokeColor: '#048df3',
                strokeWeight: 5,
            });
            hole.customData={bs:'镂空'}
            this.map.addOverlay(hole);
        });
    }
    clearMap = () => {
        let all=this.map.getOverlays()
        all.map(item=>{
            if (item.toString() === "Marker") {
                this.map.removeOverlay(item);
            }
        })
    }

    render () {
        return (
            <div className="map">
                <div className="control-box">
                    <div className="control-item" onClick={() => this.changeMap('1')}>标准地图</div>
                    <div className="control-item" onClick={() => this.changeMap('2')}>地球模式</div>
                    <div className="control-item" onClick={() => this.changeMap('3')}>普通卫星地图</div>
                    <div className="control-item" onClick={this.downloadJSON}>下载桂林市边界JSON文件</div>
                    <div className="control-item" onClick={this.changeData}>下载边界JSON文件</div>
                </div>
                <div id="map" className="map">
                </div>
            </div>
        );
    }
}

export default Map;